package com.jushu.storbox.manager;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.telephony.TelephonyManager;

import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.entities.DeviceInfo;
import com.jushu.storbox.util.PublicTools;

public class DeviceInfoManager {
	
	private Context context;

	public DeviceInfoManager(Context context) {
		// TODO Auto-generated constructor stub
		this.context = context;
	}
	
	public DeviceInfo getDeviceInfo() {
		DeviceInfo deviceInfo = new DeviceInfo();
		deviceInfo.setDeviceName(android.os.Build.MODEL.trim());
		deviceInfo.setDeviceOS("Android " + android.os.Build.VERSION.RELEASE.trim());
		deviceInfo.setDeviceSN(getOther(context));
		deviceInfo.setDeviceType(2);
		deviceInfo.setDeviceAddress(getIpAddress());
		//
		deviceInfo.setDeviceAgent(PublicTools.getVersionName(context));
		
		return deviceInfo;
	}
	
	/*
	 * 
	 * <uses-permission android:name="android.permission.READ_PHONE_STATE" />
	 */
	private String getOther(Context context) {
//		String[] phoneInfo = new String[3];
		SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
		Editor editor = settings.edit();
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String deviceIMEI = tm.getDeviceId();
		if (null == deviceIMEI || "".equals(deviceIMEI.trim())) {
			deviceIMEI = settings.getString(ClientConfig.DEVICEINFO_IMEI, "");
			if (null == deviceIMEI || "".equals(deviceIMEI.trim())) {
				deviceIMEI = "0123456789";
			}
		} else {
			editor.putString(ClientConfig.DEVICEINFO_IMEI, "");
			editor.commit();
		}
//		phoneInfo[1] = tm.getDeviceId();
//		phoneInfo[0] = tm.getNetworkOperatorName();
//		phoneInfo[2] = tm.getSimSerialNumber();
		return deviceIMEI;
	}
	
	private String getIpAddress() {
		String ipAddress = "";
		try {
			Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces();
			if (null != en) {
				while (en.hasMoreElements()) {
					NetworkInterface networkInterface = (NetworkInterface) en
							.nextElement();
					Enumeration<InetAddress> enumIpAddr = networkInterface
							.getInetAddresses();
					if (null != enumIpAddr) {
						while (enumIpAddr.hasMoreElements()) {
							InetAddress inetAddress = (InetAddress) enumIpAddr
									.nextElement();
							if (!inetAddress.isLoopbackAddress()
									&& (inetAddress instanceof Inet4Address)) {
								ipAddress = inetAddress.getHostAddress()
										.toString();
								break;
							}
						}
					}
				}
			}
		} catch (Exception ex) {
			ipAddress = "";
		}
		return ipAddress;
	}
}
